﻿using Nop.Admin.Models.Common;
using Nop.Admin.Models.XJ;
using Nop.Core;
using Nop.Core.Domain.XJ;
using Nop.Services.Common;
using Nop.Services.Customers;
using Nop.Services.Directory;
using Nop.Services.Logging;
using Nop.Services.Media;
using Nop.Services.Security;
using Nop.Services.XJ;
using Nop.Web.Framework.Controllers;
using Nop.Web.Framework.Kendoui;
using Senparc.Weixin.MP.Containers;
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace Nop.Admin.Controllers
{
	public class InspectionPlanController : BaseAdminController
	{
		#region Fields
		private readonly static string appId = "wx254193524213940e";
		private readonly static string appSecret = "c020d4fcaceaef04d03194bcf408ba51";
		private readonly IPermissionService _permissionService;
		private readonly IPictureService _pictureService;
		private readonly IWorkContext _workContext;
		private readonly IDepartmentService _departmentService;
		private readonly ICustomerService _customerService;
		private readonly IGenericAttributeService _genericAttributeService;
		private readonly IXJPlaceService _xjPlaceService;
		private readonly IXJEquipmentCategoryService _xJEquipmentCategoryService;
		private readonly IXJEquipmentService _xJEquipmentService;
		private readonly IXJEquipmentStockService _xJEquipmentStockService;
		private readonly IXJInspectionService _xJInspectionService;
		private readonly IXJInspectionPlanService _xJInspectionPlanService;
		private readonly IXJMaintenanceService _xJMaintenanceService;
		private readonly IXJMaintenanceCommentService _xJMaintenanceCommentService;
		private readonly IXJInspectionPlanLossService _xJInspectionPlanLossService;
		private readonly ICustomerActivityService _customerActivityService;
		private readonly IMessageService _messageService;
		private readonly ILogger _logger;
		#endregion

		#region Constructors
		public InspectionPlanController(IPermissionService permissionService,
			IPictureService pictureService,
			IWorkContext workContext,
			IDepartmentService departmentService,
			ICustomerService customerService,
			IGenericAttributeService genericAttributeService,
			IXJPlaceService xjPlaceService,
			IXJEquipmentCategoryService xJEquipmentCategoryService,
			IXJEquipmentService xJEquipmentService,
			IXJEquipmentStockService xJEquipmentStockService,
			IXJInspectionService xJInspectionService,
			IXJInspectionPlanService xJInspectionPlanService,
			IXJMaintenanceService xJMaintenanceService,
			IXJMaintenanceCommentService xJMaintenanceCommentService,
			IXJInspectionPlanLossService xJInspectionPlanLossService,
			ICustomerActivityService customerActivityService,
			IMessageService messageService,
			ILogger logger)
		{
			this._permissionService = permissionService;
			this._pictureService = pictureService;
			this._workContext = workContext;
			this._departmentService = departmentService;
			this._customerService = customerService;
			this._genericAttributeService = genericAttributeService;
			this._xjPlaceService = xjPlaceService;
			this._xJEquipmentCategoryService = xJEquipmentCategoryService;
			this._xJEquipmentService = xJEquipmentService;
			this._xJEquipmentStockService = xJEquipmentStockService;
			this._xJInspectionService = xJInspectionService;
			this._xJInspectionPlanService = xJInspectionPlanService;
			this._xJMaintenanceService = xJMaintenanceService;
			this._xJMaintenanceCommentService = xJMaintenanceCommentService;
			this._xJInspectionPlanLossService = xJInspectionPlanLossService;
			this._customerActivityService = customerActivityService;
			this._messageService = messageService;
			this._logger = logger;
		}
		#endregion

		#region Utilities

		[NonAction]
		protected virtual void PrepareAllTypesModel(InspectionPlanModel model)
		{
			if (model == null)
				throw new ArgumentNullException("model");

			Type enumInspectionType = typeof(InspectionTypeEnum);
			Enum.GetNames(enumInspectionType).ToList().ForEach(s =>
			{
				string value = Enum.Format(enumInspectionType, Enum.Parse(enumInspectionType, s), "d");
				model.AvailableTypes.Add(new SelectListItem { Text = s, Value = value });
			});

			Type enumAim = typeof(AimTypeEnum);
			Enum.GetNames(enumAim).ToList().ForEach(s =>
			{
				string value = Enum.Format(enumAim, Enum.Parse(enumAim, s), "d");
				model.AvailableAims.Add(new SelectListItem { Text = s, Value = value });
			});

			var categorys = _xJEquipmentCategoryService.GetAllXJEquipmentCategorys().Where(m => m.PId == 0 && !m.IsConsumables);
			foreach (var c in categorys)
				model.AvailableCategorys.Add(new SelectListItem { Text = c.Name, Value = c.Id.ToString() });

			var places = _xjPlaceService.GetAllPlaces(showHidden: false);
			foreach (var p in places)
				model.AvailablePlaces.Add(new SelectListItem { Text = p.Name, Value = p.Id.ToString() });

			model.AvailableDepartments.Add(new SelectMenuModel
			{
				name = "请选择",
				id = 0,
				open = true,
			});
			var departments = _departmentService.GetAllDepartments(showHidden: false);
			foreach (var c in departments)
			{
				model.AvailableDepartments.Add(new SelectMenuModel { name = c.Name, id = c.Id, pId = c.PId });
				if (c.IsMaintenance)
				{
					model.AvailableMaintenanceDepartments.Add(new SelectMenuModel { name = c.Name, id = c.Id, pId = c.PId });
				}
			}
			model.AvailableUsers.Add(new SelectListItem
			{
				Text = "全部",
				Value = "0"
			});
			if (model.TeamId > 0)
			{
				var users = _customerService.GetAllCustomers(
					//customerRoleIds: new[] { _customerService.GetCustomerRoleBySystemName(SystemCustomerRoleNames.Registered).Id },
					departId: model.TeamId).ToList();
				foreach (var u in users)
				{
					model.AvailableUsers.Add(new SelectListItem
					{
						Text = u.TrueName ?? u.Username,
						Value = u.Id.ToString(),
						Selected = model.TeamId == u.Id
					});
				}
			}
			model.AvailableMaintenanceUsers.Add(new SelectListItem
			{
				Text = "全部",
				Value = "0"
			});
			if (model.MaintenanceTeamId > 0)
			{
				var users = _customerService.GetAllCustomers(
					//customerRoleIds: new[] { _customerService.GetCustomerRoleBySystemName(SystemCustomerRoleNames.Registered).Id },
					departId: model.MaintenanceTeamId).ToList();
				foreach (var u in users)
				{
					model.AvailableMaintenanceUsers.Add(new SelectListItem
					{
						Text = u.TrueName ?? u.Username,
						Value = u.Id.ToString(),
						Selected = model.TeamId == u.Id
					});
				}
			}
		}

		#endregion

		#region List
		public ActionResult Index()
		{
			return RedirectToAction("List");
		}

		public virtual ActionResult List()
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageInspectionPlans))
				return AccessDeniedView();

			var model = new InspectionPlanListModel();

			model.AvailableTypes.Add(new SelectListItem
			{
				Text = "全部",
				Value = "0"
			});
			Type enumInspectionType = typeof(InspectionTypeEnum);
			Enum.GetNames(enumInspectionType).ToList().ForEach(s =>
			{
				string value = Enum.Format(enumInspectionType, Enum.Parse(enumInspectionType, s), "d");
				model.AvailableTypes.Add(new SelectListItem { Text = s, Value = value });
			});
			model.AvailableAims.Add(new SelectListItem
			{
				Text = "全部",
				Value = "0"
			});
			Type enumAim = typeof(AimTypeEnum);
			Enum.GetNames(enumAim).ToList().ForEach(s =>
			{
				string value = Enum.Format(enumAim, Enum.Parse(enumAim, s), "d");
				model.AvailableAims.Add(new SelectListItem { Text = s, Value = value });
			});
			model.AvailableCategorys.Add(new SelectListItem
			{
				Text = "全部",
				Value = "0"
			});
			var categorys = _xJEquipmentCategoryService.GetAllXJEquipmentCategorys().Where(m => m.PId == 0 && !m.IsConsumables);
			foreach (var c in categorys)
				model.AvailableCategorys.Add(new SelectListItem { Text = c.Name, Value = c.Id.ToString() });
			model.AvailablePlaces.Add(new SelectListItem
			{
				Text = "全部",
				Value = "0"
			});
			var places = _xjPlaceService.GetAllPlaces(showHidden: false);
			foreach (var p in places)
				model.AvailablePlaces.Add(new SelectListItem { Text = p.Name, Value = p.Id.ToString() });
			model.AvailableDepartments.Add(new SelectMenuModel
			{
				name = "全部",
				id = 0,
				open = true,
			});
			var departments = _departmentService.GetAllDepartments(showHidden: false);
			foreach (var c in departments)
				model.AvailableDepartments.Add(new SelectMenuModel { name = c.Name, id = c.Id, pId = c.PId });
			return View(model);
		}

		[HttpPost]
		public virtual ActionResult List(DataSourceRequest command, InspectionPlanListModel model)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageInspectionPlans))
				return AccessDeniedKendoGridJson();

			var categories = _xJInspectionPlanService.GetAllInspectionPlans(
				typeId: model.SearchTypeId,
				aimId: model.SearchAimId,
				categoryId: model.SearchCategoryId,
				placeId: model.SearchPlaceId,
				departId: model.SearchDepartId,
				no: model.SearchPNo,
				name: model.SearchName,
				pageIndex: command.Page - 1,
				pageSize: command.PageSize);
			var gridModel = new DataSourceResult
			{
				Data = categories.Select(x =>
				{
					x.TypeName = Enum.GetName(typeof(InspectionTypeEnum), x.TypeId);
					if (string.IsNullOrEmpty(x.Name))
					{
						switch (x.AimId)
						{
							case (int)AimTypeEnum.设备分类:
								x.Name = string.Join(",", x.Categorys.Where(m => !m.Deleted && m.Published).Select(d => d.Name).ToArray());
								x.Categorys = null;
								break;
							case (int)AimTypeEnum.巡检点:
								x.Name = string.Join(",", x.Places.Where(m => !m.Deleted && m.Published).Select(d => d.Name).ToArray());
								x.Places = null;
								break;
							default:
								break;
						}
					}
					return x;
				}),
				Total = categories.TotalCount
			};
			return Json(gridModel);
		}
		#endregion

		#region Create / Edit / Delete

		public virtual ActionResult Create()
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageInspectionPlans))
				return AccessDeniedView();

			var model = new InspectionPlanModel
			{
				TypeId = (int)InspectionTypeEnum.日巡检,
				AimId = (int)AimTypeEnum.设备分类,
				Published = true,
			};
			//categories
			PrepareAllTypesModel(model);

			return View(model);
		}

		[HttpPost, ParameterBasedOnFormName("save-continue", "continueEditing")]
		public virtual ActionResult Create(InspectionPlanModel model, bool continueEditing)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageInspectionPlans))
				return AccessDeniedView();

			if (ModelState.IsValid)
			{
				var categorys = _xJEquipmentCategoryService.GetAllXJEquipmentCategorys().Where(m => m.PId == 0);
				var places = _xjPlaceService.GetAllPlaces(showHidden: false);
				var equipment = new XJInspectionPlan
				{
					PNo = _xJInspectionPlanService.GenerateNo(),
					Name = model.Name,
					TypeId = model.TypeId,
					AimId = model.AimId,
					TeamId = model.TeamId,
					PersonId = model.PersonId,
					MaintenanceTeamId = model.MaintenanceTeamId,
					MaintenancePersonId = model.MaintenancePersonId,
					StartOn = model.StartOn,
					EndOn = model.EndOn,
					Published = model.Published,
					CustomerId = _workContext.CurrentCustomer.Id,
					CreatedOn = DateTime.Now,
				};
				_xJInspectionPlanService.InsertXJInspectionPlan(equipment);
				switch (model.AimId)
				{
					case (int)AimTypeEnum.设备分类:
						if (model.CategoryIds.Any())
						{
							foreach (var cId in model.CategoryIds)
							{
								var category = categorys.FirstOrDefault(m => m.Id == cId);
								if (null != category)
								{
									equipment.Categorys.Add(category);
								}
							}
							_xJInspectionPlanService.UpdateXJInspectionPlan(equipment);
						}
						break;
					case (int)AimTypeEnum.巡检点:
						if (model.PlaceIds.Any())
						{
							foreach (var cId in model.PlaceIds)
							{
								var place = places.FirstOrDefault(m => m.Id == cId);
								if (null != place)
								{
									equipment.Places.Add(place);
								}
							}
							_xJInspectionPlanService.UpdateXJInspectionPlan(equipment);
						}
						break;
					default:
						break;
				}
				//activity log
				_customerActivityService.InsertActivity("AddNewInspectionPlan", "新增巡检计划：{0}", equipment.Id);

				SuccessNotification("保存成功");

				if (continueEditing)
				{
					//selected tab
					SaveSelectedTabName();

					return RedirectToAction("Edit", new { id = equipment.Id });
				}
				return RedirectToAction("List");
			}
			//categories
			PrepareAllTypesModel(model);

			return View(model);
		}

		public virtual ActionResult Edit(int id)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageInspectionPlans))
				return AccessDeniedView();

			var plan = _xJInspectionPlanService.GetXJInspectionPlanById(id);
			if (plan == null || plan.Deleted)
				//No equipment found with the specified id
				return RedirectToAction("List");

			var model = new InspectionPlanModel
			{
				Id = plan.Id,
				PNo = plan.PNo,
				Name = plan.Name,
				TypeId = plan.TypeId,
				AimId = plan.AimId,
				CategoryIds = plan.Categorys.Select(x => x.Id).ToList(),
				CategoryNames = string.Join(",", plan.Categorys.Select(x => x.Name)),
				PlaceIds = plan.Places.Select(x => x.Id).ToList(),
				PlaceNames = string.Join(",", plan.Places.Select(x => x.Name)),
				TeamId = plan.TeamId,
				PersonId = plan.PersonId,
				MaintenanceTeamId = plan.MaintenanceTeamId,
				MaintenancePersonId = plan.MaintenancePersonId,
				StartOn = plan.StartOn,
				EndOn = plan.EndOn,
				Published = plan.Published,
				CustomerId = plan.CustomerId,
				CreatedOn = plan.CreatedOn,
			};
			//categories
			PrepareAllTypesModel(model);

			return View(model);
		}

		[HttpPost, ParameterBasedOnFormName("save-continue", "continueEditing")]
		public virtual ActionResult Edit(InspectionPlanModel model, bool continueEditing)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageInspectionPlans))
				return AccessDeniedView();

			var plan = _xJInspectionPlanService.GetXJInspectionPlanById(model.Id);
			if (plan == null || plan.Deleted)
				//No equipment found with the specified id
				return RedirectToAction("List");

			if (ModelState.IsValid)
			{
				var categorys = _xJEquipmentCategoryService.GetAllXJEquipmentCategorys().Where(m => m.PId == 0);
				var places = _xjPlaceService.GetAllPlaces(showHidden: false);
				plan.Name = model.Name;
				plan.TypeId = model.TypeId;
				plan.AimId = model.AimId;
				plan.TeamId = model.TeamId;
				plan.PersonId = model.PersonId;
				plan.MaintenanceTeamId = model.MaintenanceTeamId;
				plan.MaintenancePersonId = model.MaintenancePersonId;
				plan.StartOn = model.StartOn;
				plan.EndOn = model.EndOn;
				plan.Published = model.Published;
				switch (model.AimId)
				{
					case (int)AimTypeEnum.设备分类:
						if (model.CategoryIds.Any())
						{
							var deleteList = plan.Categorys.Where(m => !model.CategoryIds.Contains(m.Id)).ToList();
							foreach (var category in deleteList)
							{
								plan.Categorys.Remove(category);
							}
							foreach (var cId in model.CategoryIds)
							{
								if (plan.Categorys.Count(cr => cr.Id == cId) == 0)
								{
									var category = categorys.FirstOrDefault(m => m.Id == cId);
									if (null != category)
									{
										plan.Categorys.Add(category);
									}
								}
							}
						}
						plan.Places.Clear();
						_xJInspectionPlanService.UpdateXJInspectionPlan(plan);
						break;
					case (int)AimTypeEnum.巡检点:
						if (model.PlaceIds.Any())
						{
							var deleteList = plan.Places.Where(m => !model.PlaceIds.Contains(m.Id)).ToList();
							foreach (var place in deleteList)
							{
								plan.Places.Remove(place);
							}
							foreach (var cId in model.PlaceIds)
							{
								if (plan.Places.Count(cr => cr.Id == cId) == 0)
								{
									var place = places.FirstOrDefault(m => m.Id == cId);
									if (null != place)
									{
										plan.Places.Add(place);
									}
								}
							}
						}
						plan.Categorys.Clear();
						_xJInspectionPlanService.UpdateXJInspectionPlan(plan);
						break;
					default:
						break;
				}
				//activity log
				_customerActivityService.InsertActivity("EditInspectionPlan", "编辑巡检计划：{0}", plan.Id);
				if (continueEditing)
				{
					//selected tab
					SaveSelectedTabName();

					return RedirectToAction("Edit", new { id = plan.Id });
				}
				return RedirectToAction("List");
			}
			//categories
			PrepareAllTypesModel(model);

			return View(model);
		}

		public virtual ActionResult View(int id)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageInspectionPlans))
				return AccessDeniedView();

			var plan = _xJInspectionPlanService.GetXJInspectionPlanById(id);
			if (plan == null || plan.Deleted)
				//No equipment found with the specified id
				return RedirectToAction("List");

			var u = _workContext.CurrentCustomer;
			if (null == u)
				return Json(new { success = true, msg = "用户无效" });

			// 生成漏检记录
			_xJInspectionPlanService.AddLoss(customer: u, plan: plan);

			var model = new InspectionPlanModel
			{
				Id = plan.Id,
				PNo = plan.PNo,
				Name = plan.Name,
				TypeId = plan.TypeId,
				TypeName = Enum.GetName(typeof(InspectionTypeEnum), plan.TypeId),
				AimId = plan.AimId,
				AimName = Enum.GetName(typeof(AimTypeEnum), plan.AimId),
				CategoryIds = plan.Categorys.Select(x => x.Id).ToArray(),
				PlaceIds = plan.Places.Select(x => x.Id).ToArray(),
				TeamId = plan.TeamId,
				PersonId = plan.PersonId,
				MaintenanceTeamId = plan.MaintenanceTeamId,
				MaintenancePersonId = plan.MaintenancePersonId,
				StartOn = plan.StartOn,
				EndOn = plan.EndOn,
				LastUpdateOn = plan.LastUpdateOn,
				LossTime = plan.LossTime,
				Published = plan.Published,
				CustomerId = plan.CustomerId,
				CreatedOn = plan.CreatedOn
			};
			switch (plan.AimId)
			{
				case (int)AimTypeEnum.设备分类:
					model.Content = string.Join(",", plan.Categorys.Where(m => !m.Deleted && m.Published).Select(d => d.Name).ToArray());
					break;
				case (int)AimTypeEnum.巡检点:
					model.Content = string.Join(",", plan.Places.Where(m => !m.Deleted && m.Published).Select(d => d.Name).ToArray());
					break;
				default:
					break;
			}
			if (plan.TeamId > 0)
			{
				model.TeamName = _departmentService.GetNameById(plan.TeamId);
			}
			if (plan.PersonId > 0)
			{
				model.PersonName = _customerService.GetNameById(plan.PersonId);
			}
			if (plan.MaintenanceTeamId > 0)
			{
				model.MaintenanceTeamName = _departmentService.GetNameById(plan.MaintenanceTeamId);
			}
			if (plan.MaintenancePersonId > 0)
			{
				model.MaintenancePersonName = _customerService.GetNameById(plan.MaintenancePersonId);
			}
			return View(model);
		}

		[HttpPost]
		public virtual ActionResult Delete(int id)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageInspectionPlans))
				return AccessDeniedView();

			var plan = _xJInspectionPlanService.GetXJInspectionPlanById(id);
			if (plan == null)
				//No equipment found with the specified id
				return RedirectToAction("List");

			_xJInspectionPlanService.DeleteInspectionPlan(plan);

			//activity log
			_customerActivityService.InsertActivity("DeleteInspectionPlan", "删除设施设备：{0}", plan.Id);

			SuccessNotification("删除成功");
			return RedirectToAction("List");
		}

		/// <summary>
		/// 发送巡检日志
		/// </summary>
		/// <param name="id"></param>
		/// <param name="templateId"></param>
		/// <returns></returns>
		public async Task<JsonResult> SubscribeMessage(int id, string templateId = "nQpdDl04GLhjY7EwrF3rk6orDUEI_WcDQ3lp5FUg09k")
		{
			await AccessTokenContainer.RegisterAsync(appId, appSecret);

			var plan = _xJInspectionPlanService.GetXJInspectionPlanById(id);
			if (null == plan || plan.Deleted)
				return Json(new { success = false, msg = "计划无效" });
			var inspections = _xJInspectionService.GetAllInspections(planId: id);
			if (!inspections.Any())
				return Json(new { success = false, msg = "无需发送" });

			var u = _workContext.CurrentCustomer;
			if (null == u)
				return Json(new { success = true, msg = "用户无效" });

			//try
			//{
			//	foreach (var item in inspections)
			//	{

			//		var templateMessageData = new TemplateMessageData
			//		{
			//			["thing1"] = new TemplateMessageDataValue(item.EquipmentName + "巡检计划"),
			//			["date2"] = new TemplateMessageDataValue(item.StartOn.ToString("yyyy年MM月dd日 HH:mm"))
			//		};

			//		string page = "pages/inspection/detail";
			//		List<string> openIds = new List<string>();
			//		string msg = string.Empty;
			//		bool hasFinished = false;

			//		if (plan.PersonId > 0)
			//		{
			//			var customer = _customerService.GetCustomerById(plan.PersonId);
			//			string openId = customer.GetAttribute<string>(SystemCustomerAttributeNames.OpenId);
			//			if (!string.IsNullOrEmpty(openId))
			//			{
			//				openIds.Add(openId);
			//			}
			//		}
			//		else
			//		{
			//			var dCustomers = _customerService.GetAllCustomers(departId: plan.TeamId);
			//			if (dCustomers.Any())
			//			{
			//				foreach (var c in dCustomers)
			//				{
			//					string openId = c.GetAttribute<string>(SystemCustomerAttributeNames.OpenId);
			//					if (!string.IsNullOrEmpty(openId))
			//					{
			//						openIds.Add(openId);
			//					}
			//				}
			//			}
			//			//var tCustomers = _customerService.GetAllCustomers(teamId: message.AimSourceId);
			//			//if (tCustomers.Any())
			//			//{
			//			//	foreach (var c in tCustomers)
			//			//	{
			//			//		string openId = c.GetAttribute<string>(SystemCustomerAttributeNames.OpenId);
			//			//		if (!string.IsNullOrEmpty(openId))
			//			//		{
			//			//			openIds.Add(openId);
			//			//		}
			//			//	}
			//			//}
			//		}
			//		foreach (var openId in openIds)
			//		{
			//			var result = await MessageApi.SendSubscribeAsync(appId, openId, templateId, templateMessageData, page);
			//			if (result.errcode == ReturnCode.请求成功)
			//			{
			//				hasFinished = true;
			//			}
			//			else
			//			{
			//				msg = "消息发送失败";
			//				_logger.Error(result.errmsg);
			//			}
			//		}
			//		if (!hasFinished && !string.IsNullOrEmpty(msg))
			//			return Json(new { success = false, msg });
			//		else
			//		{
			//			//message.IsFinished = true;
			//			//_messageService.UpdateMessage(message);
			//			return Json(new { success = true, msg = "消息已发送" });
			//		}
			//	}
			//}
			//catch (Exception ex)
			//{
			//	_logger.Error(ex.Message);
			//	return Json(new { success = false, msg = "消息发送失败" });
			//}
			return Json(new { success = false, msg = "消息发送失败" });
		}

		#endregion

		#region Inspections

		[HttpPost]
		public virtual ActionResult Inspections(DataSourceRequest command, int planId)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageInspectionPlans))
				return AccessDeniedKendoGridJson();

			var categories = _xJInspectionService.GetInspectionHistorys(
				planId: planId,
				pageIndex: command.Page - 1,
				pageSize: command.PageSize);
			var gridModel = new DataSourceResult
			{
				Data = categories.Select(x =>
				{
					return x;
				}),
				Total = categories.TotalCount
			};
			return Json(gridModel);
		}
		#endregion

		#region Maintenances

		[HttpPost]
		public virtual ActionResult Maintenances(DataSourceRequest command, int planId)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageInspectionPlans))
				return AccessDeniedKendoGridJson();

			var categories = _xJMaintenanceService.GetAllMaintenances(
				planId: planId,
				pageIndex: command.Page - 1,
				pageSize: command.PageSize);
			var gridModel = new DataSourceResult
			{
				Data = categories.Select(x =>
				{
					x.StateName = Enum.GetName(typeof(MaintenanceStateEnum), x.State);
					return x;
				}),
				Total = categories.TotalCount
			};
			return Json(gridModel);
		}
		#endregion

		#region Losss

		[HttpPost]
		public virtual ActionResult Losss(DataSourceRequest command, int planId)
		{
			if (!_permissionService.Authorize(StandardPermissionProvider.ManageInspectionPlans))
				return AccessDeniedKendoGridJson();

			var categories = _xJInspectionPlanLossService.GetXJInspectionPlanLosss(
				planId: planId,
				pageIndex: command.Page - 1,
				pageSize: command.PageSize);
			var gridModel = new DataSourceResult
			{
				Data = categories.Select(x =>
				{
					return x;
				}),
				Total = categories.TotalCount
			};
			return Json(gridModel);
		}
		#endregion

	}
}